@file:Suppress("OVERRIDE_DEPRECATION")

package com.ly.nethub.netty.tcp

import com.ly.nethub.interf.IDisconnectHandler
import com.ly.nethub.interf.ITaskManager
import com.ly.nethub.utils.LogUtils
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter

internal class NettyTcpReadHandler(
    private val taskManager: ITaskManager,
    private val disconnectHandler: IDisconnectHandler
) : ChannelInboundHandlerAdapter() {

    override fun channelActive(ctx: ChannelHandlerContext?) {
        super.channelActive(ctx)
        LogUtils.d("$TAG channelActive() ctx = $ctx")
    }

    override fun channelInactive(ctx: ChannelHandlerContext?) {
        super.channelInactive(ctx)
        LogUtils.w("$TAG channelInactive() ctx = $ctx")
        //通道断开连接
        closeChannelAndReconnect(ctx, null)
    }


    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        super.exceptionCaught(ctx, cause)
        LogUtils.e("$TAG exceptionCaught() ctx = $ctx ,\t cause = $cause")
        closeChannelAndReconnect(ctx, cause)
    }

    override fun channelRead(ctx: ChannelHandlerContext?, msg: Any?) {
        super.channelRead(ctx, msg)
        LogUtils.d("$TAG channelRead() ctx = $ctx ,\t msg = $msg")
        taskManager.onMsgReceived(msg)
    }


    /**
     * 关闭并且重连
     */
    private fun closeChannelAndReconnect(ctx: ChannelHandlerContext?, cause: Throwable?) {
        LogUtils.d(
            "$TAG 准备关闭channel 并且重连," +
                    "cause:$cause" +
                    "remoteAddress:${ctx?.channel()?.remoteAddress()}"
        )
        ctx?.channel()?.close()
        disconnectHandler.handleUnexpectedDisconnection(cause)
    }

    companion object {
        private const val TAG = "NettyTCPReadHandler"
    }
}